package cn.rkylin.oms.item.controller;

import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.rkylin.core.controller.ApolloController;
import cn.rkylin.oms.common.dto.DBLog;
import cn.rkylin.oms.common.utils.DateUtil;
import cn.rkylin.oms.common.utils.LogUtil;
import cn.rkylin.oms.item.adapter.ItemAdapter;
import cn.rkylin.oms.item.adapter.ItemAdapterFactory;

/**
 * 自动下载指定店铺的商品
 *
 * @author jipengcheng
 * @created 2017.5.17
 */
@Controller
@RequestMapping("/itemManager")
public class ItemController extends ApolloController {
    private static final Log logger = LogFactory.getLog(ItemController.class);
    private static final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Autowired
    LogUtil logUtil;

    /**
     * 根据平台商品编码获取商品
     * http://localhost:8081/itemManager/getItemByItemCode.action
     *
     * @param shopId
     * @param itemCode
     * @return
     * @author jipengcheng
     */
    @SuppressWarnings("rawtypes")
    @ResponseBody
    @RequestMapping(value = "/getItemByItemCode", method = RequestMethod.GET)
    public Map getItemByItemCode(String shopId, String itemCode) {
        // 返回值
        Map<String, Object> resultMap = new HashMap<String, Object>();

        try {
            if (StringUtils.isBlank(shopId)) {
                resultMap.put("success", "false");
                resultMap.put("msg", "shopId is null");
                return resultMap;
            }

            ItemAdapter adapter = ItemAdapterFactory.getItemAdapter(shopId);
            if (adapter == null) {
                resultMap.put("success", "false");
                resultMap.put("msg", "ItemAdapter is null");
                return resultMap;
            }

            Map<String, Object> reqMap = new HashMap<String, Object>();
            reqMap.put("itemCode", itemCode);

            int r = adapter.downloadByItemCode(shopId, reqMap);
            if (r == 0) {
                resultMap.put("success", "false");
            } else {
                resultMap.put("success", "true");
            }

        } catch (Exception e) {
            resultMap.put("success", "false");
            resultMap.put("msg", e.getMessage());

            logUtil.error(new DBLog("", "job_exception", "getItemByItemCode",
                    e.getMessage()), e);
        }

        return resultMap;

    }

    /**
     * 自动下载指定店铺的商品
     * http://localhost:8080/OMSJobExecutor/itemManager/getItemAll.action
     *
     * @param shopid 指定的店铺
     * @param start  开始时间
     * @param end    结束时间
     * @return
     * @throws Exception
     */
    @SuppressWarnings("rawtypes")
    @ResponseBody
    @RequestMapping(value = "/getItemAll", method = RequestMethod.GET)
    public Map getItemAll(String shopId, String start, String end) {

        // shopId = "f8df6b12655d4b6abc213c339e538472";
        // end = "2017-06-16 23:59:59";

        // 返回值
        Map<String, Object> resultMap = new HashMap<String, Object>();

        try {
            if (StringUtils.isBlank(shopId)) {
                resultMap.put("success", "false");
                resultMap.put("msg", "shopId is null");
                return resultMap;
            }

            if (StringUtils.isEmpty(start) && StringUtils.isNotEmpty(end)) {
                Calendar c = Calendar.getInstance();
                c.setTime(simpleDateFormat.parse(end));
                c.add(Calendar.MONTH, -12); // 得到前1年
                start = simpleDateFormat.format(c.getTime());
            }
            start = URLDecoder.decode(start, "UTF-8");
            end = URLDecoder.decode(end, "UTF-8");
            logger.debug("【jobExec.start】" + start);
            logger.debug("【jobExec.end】" + end);

            ItemAdapter adapter = ItemAdapterFactory.getItemAdapter(shopId);
            if (adapter == null) {
                resultMap.put("success", "false");
                resultMap.put("msg", "ItemAdapter is null");
                return resultMap;
            }

            Map<String, Object> reqMap = new HashMap<String, Object>();
            reqMap.put("startTime", start);
            reqMap.put("endTime", end);

            int r = adapter.downloadByModifyTime(shopId, reqMap);
            if (r == 0) {
                resultMap.put("success", "false");
            } else {
                resultMap.put("success", "true");
            }

        } catch (Exception e) {
            resultMap.put("success", "false");
            resultMap.put("msg", e.getMessage());

            logUtil.error(new DBLog("", "job_exception", "getItemAll",
                    e.getMessage()), e);

        }
        return resultMap;
    }

    /**
     * 手动同步库存根据商品
     * http://localhost:8080/OMSJobExecutor/itemManager/manualSynchStock.action
     *
     * @param shopid   指定的店铺
     * @param ecItemId 平台商品Id
     * @return 错误消息
     * @throws Exception 异常
     */
    @ResponseBody
    @RequestMapping(value = "/manualSynchStockByItem", method = RequestMethod.GET)
    public Map<String, Object> manualSynchStockByItem(String shopId, String ecItemId) throws Exception {
        Map<String, Object> resultMap = new HashMap<String, Object>();

        ItemAdapter adapter = ItemAdapterFactory.getItemAdapter(shopId);
        if (adapter == null) {
            resultMap.put("success", "false");
            resultMap.put("msg", "ItemAdapter is null");
            return resultMap;
        }

        String msg = adapter.manualSynchStockByItem(ecItemId);
        if ("".equals(msg)) {
            resultMap.put("success", "true");
            resultMap.put("msg", "");
        } else {
            resultMap.put("success", "false");
            resultMap.put("msg", msg);
        }

        return resultMap;
    }

    /**
     * 手动同步库存根据SKU
     * http://localhost:8080/OMSJobExecutor/itemManager/manualSynchStock.action
     *
     * @param shopid  指定的店铺
     * @param ecSkuId 平台规格Id
     * @return 错误消息
     * @throws Exception 异常
     */
    @ResponseBody
    @RequestMapping(value = "/manualSynchStockBySku", method = RequestMethod.GET)
    public Map<String, Object> manualSynchStockBySku(String shopId, String ecSkuId) throws Exception {
        Map<String, Object> resultMap = new HashMap<String, Object>();

        ItemAdapter adapter = ItemAdapterFactory.getItemAdapter(shopId);
        if (adapter == null) {
            resultMap.put("success", "false");
            resultMap.put("msg", "ItemAdapter is null");
            return resultMap;
        }

        String msg = adapter.manualSynchStockBySku(ecSkuId);
        if ("".equals(msg)) {
            resultMap.put("success", "true");
            resultMap.put("msg", "");
        } else {
            resultMap.put("success", "false");
            resultMap.put("msg", msg);
        }

        return resultMap;
    }

    /**
     * 自动同步店铺库存并上下架
     * http://localhost:8080/OMSJobExecutor/itemManager/autoSynchStock.action
     *
     * @param shopid 指定的店铺
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/autoSynchStock", method = RequestMethod.GET)
    public Map<String, Object> autoSynchStock(String shopId) throws Exception {
        Map<String, Object> resultMap = new HashMap<String, Object>();

        ItemAdapter adapter = ItemAdapterFactory.getItemAdapter(shopId);
        if (adapter == null) {
            resultMap.put("success", "false");
            resultMap.put("msg", "ItemAdapter is null");
            return resultMap;
        }

        String msg = adapter.autoSynchStock(shopId);
        if ("".equals(msg)) {
            resultMap.put("success", "true");
            resultMap.put("msg", "");
        } else {
            resultMap.put("success", "false");
            resultMap.put("msg", msg);
        }

        return resultMap;
    }

}
